package it.polimi.swim.servlet;

import it.polimi.swim.entity.Skill;
import it.polimi.swim.session.HelpRequestManagerBeanRemote;
import it.polimi.swim.session.SkillManagerBeanRemote;
import it.polimi.swim.session.SystemUserManagerBeanRemote;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private Context ctx;
       

    public RegistrationServlet() {
        super();
        
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String name, surname, mail, city, psw, month,day,year;
		
		try{
			Properties env = new Properties();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			
			ctx = new InitialContext();
			Object ref = ctx.lookup("SystemUserManagerBean/remote");
			SystemUserManagerBeanRemote systemUserManager = (SystemUserManagerBeanRemote) ref;
			Object ref2 = ctx.lookup("SkillManagerBean/remote");
			SkillManagerBeanRemote skillUserManager = (SkillManagerBeanRemote) ref2;
			name=request.getParameter("name");
			surname=request.getParameter("surname");
			mail=request.getParameter("mail");
			psw=request.getParameter("psw");
			city=request.getParameter("city");
			day=request.getParameter("day");
			month=request.getParameter("month");
			year=request.getParameter("year");
			
			int exist = systemUserManager.controlUserDuplicate(mail);
			if(exist==0){		
				String idSkill[] = request.getParameterValues("skill"); 	
				
				systemUserManager.createUser(name, surname, city, mail, psw, day, month, year);
				if(idSkill!=null){
					for(int i = 0; i<idSkill.length;i++){
						systemUserManager.addSkill(mail, psw, Integer.parseInt(idSkill[i]));
					}
				}
				request.setAttribute("message", "Registration was successful");
			}else{
				request.setAttribute("message", "There is already a registered user with this email");
			}
			
			request.getRequestDispatcher("/messagePage.jsp").forward(request, response);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
